package cn.bug.greenflag.service.impl;

import cn.bug.greenflag.ex.ServiceCode;
import cn.bug.greenflag.ex.ServiceException;
import cn.bug.greenflag.mapper.ManufacturerInfoMapper;
import cn.bug.greenflag.mapper.PurchaseInfoMapper;
import cn.bug.greenflag.pojo.dto.ManufacturerInfoAddNewDto;
import cn.bug.greenflag.pojo.entity.ManufacturerInfo;
import cn.bug.greenflag.pojo.vo.ManufacturerInfoVO;
import cn.bug.greenflag.service.ManufacturerInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 处理厂商信息
 * @author FT
 * @version 1.01
 * */
@Slf4j
@Service
public class ManufactureInfoServiceImpl implements ManufacturerInfoService {
    @Autowired
    ManufacturerInfoMapper manufacturerInfoMapper;
    @Autowired
    PurchaseInfoMapper purchaseInfoMapper;

    public ManufactureInfoServiceImpl() {
        log.info("创建业务对象:ManufactureInfoServiceImpl");
    }

    @Override
    public void addNew(ManufacturerInfoAddNewDto manufacturerInfoAddNewDto) {
        log.debug("开始处理【添加厂商信息】的业务,参数为:{}",manufacturerInfoAddNewDto);
        //检查厂商名称是否唯一
        String name=manufacturerInfoAddNewDto.getName();
        int count=manufacturerInfoMapper.countByName(name);
        log.debug("尝试添加的厂商名称是:{},在数据库中此厂商的数量为:{}",name,count);
        if(count>0){
            String message="添加厂商信息失败,此厂商名称已存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        //检查厂商电话是否唯一
        String phone=manufacturerInfoAddNewDto.getPhone();
        int countByphone=manufacturerInfoMapper.countByPhone(phone);
        log.debug("尝试添加的厂商电话为:{},在数据库中此号码的数据为:{}",phone,countByphone);
        if(countByphone>0){
            String message="添加厂商信息失败,此厂商的号码已存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        //添加新的厂商信息,使用entity类接收数据
        ManufacturerInfo manufacturerInfo=new ManufacturerInfo();
        BeanUtils.copyProperties(manufacturerInfoAddNewDto,manufacturerInfo);
        // 执行插入数据
        int rows = manufacturerInfoMapper.insert(manufacturerInfo);
        if (rows != 1) {
            String message = "添加厂商信息失败！服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据id删除厂商信息】的业务,需要删除的厂商id是:{}",id);
        ManufacturerInfoVO queryResult = manufacturerInfoMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "删除厂商失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        // 执行删除
        log.debug("执行删除id为{}的厂商……", id);
    }
}
